<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Utils\RedisUtils;
use App\Jobs\AliOssUploadJob;
use App\Jobs\GenerateUserCount;
use App\Models\ActivityUsers;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;

class IndexController extends Controller
{
    public function testLock(){
        $update="UPDATE goods set count=count-1 where count>0 and id=1";
        $lockUtils=new RedisUtils;
        $locked=$lockUtils->lock("goods-1",mt_rand(100001,999999));
        if(!empty($locked)){
            $less=DB::table("goods")->where("id",1)->value("count");
            if($less!=0){
                $insert="insert into buylogs(buyer,goods_id,buy_time) values($locked,1,now())";
                DB::beginTransaction();
                try{
                DB::update($update);
                DB::insert($insert);
                DB::commit();
                }catch(Exception $e){
                    DB::rollBack();
                }
                finally{
                    $lockUtils->unLock("goods-1",$locked);
                }
            return response('success');
            }
            return response('empty',500);
        }else{
            return response('lock',500);
        }
    }
    //
    public function index(){
        return view("welcome");
    }
    //
    public function calcCount(){
       $start_time=strtotime('2025-06-01 00:00:00');
       $end_time=strtotime('2025-06-30 23:59:59');
       $result=[];
       $count=DB::table("zeai_tg_user")->count();
       return DB::table("zeai_tg_user")->select(DB::raw("id, member_id, nickname, mob, grade, gradetitle, tguid"))->orderBy('regtime','desc')->chunk(100,function($users)use($start_time,$end_time,$result){
        foreach($users as $user){
            Redis::lpush("userids",$user->id);
            GenerateUserCount::dispatch($user->id,$user->member_id,$start_time,$end_time);
        }
       });
    }
    public function giteeHook(Request $request){
        $hook_name=$request['hook_name']??'gitee';
        //file_put_contents('../storage/'.$hook_name.".log",json_encode($request->all()).PHP_EOL,FILE_APPEND);
    }
    public function login(Request $request){
       if(request()->isMethod('POST')){
        $acc=$request['acc']??'';
        $pwd=$request['pwd']??'';
        if(empty($pwd)||empty($acc)){
            return response()->json(['status'=> 0,'msg'=> 'error']);
        }
        if($acc="admin" &&$pwd=="admin"){
             return response()->json(['status'=> 1,'msg'=> 'success']);
        }
        return response()->json(['status'=> 0,'msg'=> 'fail']);
       }else{
        return view('login');
       }
    }
    public function loginmobile(Request $request){
        return session("id");
    }
    public function register(Request $request){
        if(request()->isMethod('POST')){
            $acc=$request['acc']??'';
            $pwd=$request['pwd']??'';
            $mobile=$request['mobile']??'';
            $status=1;
            $user=new ActivityUsers();
            $user->acc=$acc;
            $user->pwd=$pwd;
            $user->mobile=$mobile;
            $user->status=$status;
            return $user->save();
        }else{
            return view('register');
        }
    }
    public function test(Request $request){
        $result=DB::table('tbl_test1_v1')->skip(0)->limit(5)->get();
        return response()->json($result);
    }
    private function getTblOriginFields($tableName){
        $originFieldList="describe ".$tableName;
        $result=DB::select($originFieldList);
        return Arr::pluck($result,"Field");
    }
    private function makeEncryptTrigger($tableName,$fieldList){
        $originFieldList=$this->getTblOriginFields($tableName);
        $triggerName="tr_".$tableName."_encrypt";
        $triggerSql="create trigger ".$triggerName." before insert on ".$tableName." for each row ";
        foreach($fieldList as $field){
            if(in_array($field,$originFieldList)){
                $triggerSql.="set new.".$field."=aes_encrypt(new.".$field.",'123456') ";
            }
        }
        return $triggerSql.";";
    }
    public function addEnTrigger(Request $request){
        $tableName=$request['table']??'';
        $fieldList=$request['fields']??[];
        return response()->json($this->makeEncryptTrigger($tableName,$fieldList));
    }
    public function testMongo(Request $request){
        $client=new \MongoDB\Client("mongodb://root:root123456@127.0.0.1:27017");
        $collection=$client->test->c123;
        return response()->json($collection->insertOne([
            'name'=>'allen',
            'age'=>122,
            'address'=>'张学良',
            'mobile'=>'12345678903',
            'create_time'=>time(),
            'update_time'=>time(),
            'create_user'=>'admin2',
            'update_user'=>'admin2',
            'is_delete'=>0,
            'is_active'=>1,
            'is_lock'=>0,
            'is_valid'=>1,
            'is_expired'=>0,
        ])->getInsertedId());
    }
    public function testMongo1(Request $request){
        $client=new \MongoDB\Client("mongodb://root:root123456@127.0.0.1:27017");
        $collection=$client->selectCollection('test','c123');
        $result=$collection->find(['address'=>['$regex'=>'张学']]);
        $items=$result->toArray();
        return response()->json($items);
    }
    public static function addGiteePullLog($data){
        $client=new \MongoDB\Client("mongodb://root:root123456@127.0.0.1:27017");
        $db=$client->selectDatabase("shop");
        $collection=$db->selectCollection("gitee_pull_log");
        return response()->json([
            'code'=>0,
            'msg'=>'success',
            'data'=>$collection->insertOne($data)->getInsertedId()
        ]);
    }
    public function testFireFox(Request $request){
        $url=$request['url']??'https://www.163.com';
        $approot=storage_path('app/public/');
        $filename=time();
        $ret=exec('firefox --headless --screenshot '.$approot.$filename.'.png '.$url,$v);
        echo "/storage/{$filename}.png";
        return compact('ret','v');
    }
    public function testAliOss(Request $request){
        $uid=$request['uid']??'';
        $file=$request->file("file");
        if(!empty($uid)&&$file->isValid()){
         $file=$file->move(storage_path('app/public/'),$file->getClientOriginalName());
         $this->dispatch(new AliOssUploadJob($uid,$file->getRealPath()));
        }
    }
}
